var url_ = window.location.href;
var ua = window.navigator.userAgent.toLowerCase();
var voice = {};
var userData_ = {};
var otherVoice = [];

//判断微信客户端
function isWeiXin() {
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}

//判断QQ客户端
function isQQ() {
    if (ua.match(/\sQQ/i) == "qq") {
        return true;
    } else {
        return false;
    }
}

//判断IOS
function isIos() {
    return /iphone|ipod|ipad/i.test(ua);
}

//判断安卓
function isAndroid() {
    return /android/i.test(ua);
}

//查询url字符串
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURI(r[2]);
    }
    return null;
};
//阻止默认事件
function cancelEvent(event){
window.event? window.event.returnValue = false : event.preventDefault();
}

//阻止事件冒泡
function stopBubble(){
window.event? window.event.cancelBubble = true : e.stopPropagation();
}

//弹窗提示封装
function hintModal(content){
    var text = '<span>' + content + '</span>';
    $('.modal-box').show();
    $('.modal-content').empty().append(text);
}

// 分享祝福
$('.share,.modal-share-box').on('click',function(event){
    event.preventDefault();
    stopBubble();
    if(isWeiXin()){
        $('.cover-hint').show();
    }else{
        alert('请在微信中打开链接')
    }
});
$('.cover-hint').on('click',function(event){
    event.preventDefault();
    stopBubble();
    $(this).hide();
});

if(isQQ()){
    var voiceId = GetQueryString('voiceId').substring(0,GetQueryString('voiceId').length - 1);
    var headImgUrl = GetQueryString('headImgUrl');
     //分享者录音控制与头像
    if(String(voiceId) != 'undefined'){
        $('#current-user').parent().show();
        $('.current-user-head').attr('src',headImgUrl);
    }else{
        // alert('没有获取到对应参数！');
    };
    $.ajax({
        url:'http://wxapi.ngrok.xiaomiqiu.cn/open/list_voice',
        type:'get',
        success:function(res){
            console.log('获取录音serverId:',res);
            var otherData = res.data;
                if(!!otherData){
                    for (var i = 0; i < otherData.length; ++i) {
                        ;(function(i_){
                            $($('.user-head')[i_]).attr('src',otherData[i_].headImgUrl);
                        })(i);
                    }
                }
        }
    });
}

(function(){
    //获取wx配置
    $.ajax({
        url: 'http://wxapi.ngrok.xiaomiqiu.cn/open/config?url=' + encodeURIComponent(url_),
        type: 'get',
        success: function (data) {
            var data_ = data.data;
            console.log('data_',data_)
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data_.appId, // 必填，公众号的唯一标识
                timestamp: data_.timestamp, // 必填，生成签名的时间戳
                nonceStr: data_.nonceStr, // 必填，生成签名的随机串
                signature: data_.signature,// 必填，签名，见附录1
                url:data_.url,
                jsApiList: ['startRecord','translateVoice','stopRecord','stopVoice','onVoicePlayEnd',
                            'uploadVoice','downloadVoice','playVoice','onMenuShareTimeline','onMenuShareAppMessage',
                            'onMenuShareQZone','onMenuShareQQ','onMenuShareWeibo'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });
        }
    });

    var wxShareConfig = {
        imgUrl:GetQueryString('headImgUrl'),
        title: "今年圣诞，我想让你知道",
        link:window.location.href,
        desc:"你可以听我的祝福吗？",
        success: function () { 
        },
    }

    wx.ready(function(){
        // alert('链接微信成功！标识：4');
        wx.onMenuShareTimeline(wxShareConfig);  //分享到朋友圈
        wx.onMenuShareAppMessage(wxShareConfig); //分享到微信朋友
        wx.onMenuShareQQ(wxShareConfig); //分享到QQ
        wx.onMenuShareQZone(wxShareConfig); //分享到QQ空间

        var voiceId = GetQueryString('voiceId').substring(0,GetQueryString('voiceId').length - 1);
        var headImgUrl = GetQueryString('headImgUrl');
        //分享者录音控制与头像
        if(String(voiceId) != 'undefined'){
            // alert(headImgUrl)
            $('#current-user').parent().show();
            $('.current-user-head').attr('src',headImgUrl);
            wx.downloadVoice({
                serverId: voiceId, // 需要下载的音频的服务器端ID，由uploadVoice接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                    var localId = res.localId;
                    console.log('分享者录音id',localId) // 返回音频的本地ID
                    $('#current-user').attr('data-voice',localId);
                }
            });
        }else{
            // alert('没有获取到对应参数！');
        };
        $.ajax({
            url:'http://wxapi.ngrok.xiaomiqiu.cn/open/list_voice',
            type:'get',
            success:function(res){
                console.log('获取录音serverId:',res);
                var otherData = res.data;
                    if(!!otherData){
                        for (var i = 0; i < otherData.length; ++i) {
                            ;(function(i_){
                                $($('.user-head')[i_]).attr('src',otherData[i_].headImgUrl);
                                $($('.play')[i_]).attr('data-voice',otherData[i_].voiceId);
                            })(i);
                        }
                    }
            }
        });
        // 分享者抽奖次数加一
        // $.ajax({
        //     url:'http://wxapi.ngrok.xiaomiqiu.cn/open/share_add_one?unionId=' + GetQueryString('unionId'),
        //     type:'get',
        //     success:function(res){
        //         console.log('加一结果:',res);
        //     }
        // });
        //录音与头像的数据绑定
        $.ajax({
            url:'http://wxapi.ngrok.xiaomiqiu.cn/open/list_voice',
            type:'get',
            success:function(res){
                console.log('获取录音voiceId:',res);
                var otherData = res.data;
                for (var i = 0; i < otherData.length; ++i) {
                    $($('.play')[i]).attr('data-voice',otherData[i].voiceId);
                    $($('.user-head')[i]).attr('src',otherData[i].headImgUrl);
                }
            }
        })
    });

    wx.error(function(res){
        console.log('error',res)
    });
})();

//录音控制模块
(function(){
    $('#talkBtn').on('click',function(event){
        event.preventDefault();
        if(isWeiXin()){
            window.location.href = 'http://wxweb.ngrok.xiaomiqiu.cn/?unionId=' + GetQueryString('unionId');
        }else{
           hintModal('请在微信中打开！') 
        }
    })
})();

// 底部获奖轮播
(function(){
    var loopDiv = $('.loop-box');
    var loopChild = $('.loop-box div:first-child')

    console.log(loopChild)
    var po = 0;
    var timeMachine = setInterval(function(){
        po--;
        loopDiv.css('left',po + 'px');
        var testNum = po / -185;
        // var re = /^[1-9]+[0-9]*]*$/;
        if(po == -555){
           po = 0;
        }
    },20)
})();

//礼物touch放大
$('.gifts-box > img').click(function(event){
    event.preventDefault();
    stopBubble();
    if($(this).css('transform') == 'none'){
        $(this).css({'transform':'scale(2)','z-index':'20'});
    }else{
        if($(this).css('transform') == 'matrix(1, 0, 0, 1, 0, 0)'){
        $(this).css({'transform':'scale(2)','z-index':'20'});
        }
        if($(this).css('transform') == 'matrix(2, 0, 0, 2, 0, 0)'){
            $(this).css({'transform':'scale(1)','z-index':'11'});
        }
    } 
});

(function(){
        //恢复按钮状态
    var renewPlayBtn = function(){
        console.log('111111')
        $('.stop').hide();
        $('#current-user-stop').hide();
        $('.play').show();
        $('#current-user').show();
    };

    function playVoice(id){
        // ##播放语音接口
        wx.playVoice({
            localId: id,
            success:function(res){
                wx.onVoicePlayEnd({
                    success: function (res) {
                    var localId = res.localId; // 返回音频的本地ID
                    renewPlayBtn();
                }
              });
            } // 需要播放的音频的本地ID，由stopRecord接口获得
        });
    }

    function stopVoice(id){
        wx.stopVoice({
            localId: id // 需要停止的音频的本地ID，由stopRecord接口获得
        });
    }
        //播放当前用户录音
    $('#current-user').on('click',function(event){
        event.preventDefault();
        stopBubble();
        var e  = $(event.target);
        if(isWeiXin()){
            renewPlayBtn();
            e.hide();
            $('#current-user-stop').show();
            playVoice(e.attr('data-voice'));
        }else{
            hintModal('请在微信中打开！')
        }
    });
    //停止播放
    $('#current-user-stop').on('click',function(event){
        stopBubble();
        $(event.target).hide();
        $('#current-user').show();
        stopVoice($('#current-user').attr('data-voice'))
    });

    // 其他用户
    $('.play').on('click',function(event){
        var e  = $(event.target);
        event.preventDefault();
        stopBubble();
        if(isWeiXin()){
            var serverId = $(event.target).attr('data-voice');
            wx.downloadVoice({
                serverId: serverId, // 需要下载的音频的服务器端ID，由uploadVoice接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                    var localId = res.localId;// 返回音频的本地ID
                    playVoice(localId);
                    renewPlayBtn();
                    e.hide();
                    e.parent().find('.stop').show();
                    $('.stop').on('click',function(event){
                        event.preventDefault();
                        stopBubble();
                        var e  = $(event.target);
                        e.hide();
                        e.parent().find('.play').show();
                        stopVoice(localId);
                    });
                }
            });
        }else{
            hintModal('请在微信中打开！')
        }
    });
})();

$('.modal-box').on('click',function(event){
    event.preventDefault();
    $(this).hide(); 
});

// 分享祝福与我的礼物
(function(){
    $('.my-gift').on('click',function(event){
        event.preventDefault();
        $('.my-gift-page').slideDown();
    });
    $('.back-home').on('click',function(event){
        event.preventDefault();
        $('.my-gift-page').slideUp();
        $('.rule-page').slideUp();
    });
    $('.rule').on('click',function(event){
        event.preventDefault();
        $('.rule-page').slideDown();
    })
})()





